<?php
/**
 * golangshop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 杭州瑞璞玉数字科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.golangshop.com
 * =========================================================
 */


namespace addon\store\event;

use addon\pointexchange\model\Exchange;
use addon\pointexchange\model\Order;
use addon\store\model\StoreMember as StoreMemberModel;
use addon\store\model\StoreGoodsSku;

/**
 * 积分兑换订单创建之后
 */
class PointExchangeOrderCreate
{

    // 行为扩展的执行入口必须是run
    public function handle($data)
    {
        $order_model = new Order();
        $order_info = $order_model->getOrderInfo([ [ 'order_id', '=', $data[ 'order_id' ] ] ], 'site_id,member_id,delivery_store_id,exchange_goods_id,num')[ 'data' ];
        if (!empty($order_info) && !empty($order_info[ 'delivery_store_id' ])) {
            //添加店铺关注记录
            $shop_member_model = new StoreMemberModel();
            $res = $shop_member_model->addStoreMember($order_info[ 'delivery_store_id' ], $order_info[ 'member_id' ]);
            if ($res[ "code" ] < 0) {
                return $res;
            }

            $goods_info = ( new Exchange() )->getExchangeInfo($order_info[ 'exchange_goods_id' ])[ 'data' ];
            if (empty($goods_info)) return error(-1, '未获取到兑换商品信息', '');

            $store_goods_sku_model = new StoreGoodsSku();
            $stock_result = $store_goods_sku_model->decStock([ "store_id" => $order_info[ "delivery_store_id" ], "sku_id" => $goods_info[ "sku_id" ], 'stock' => $order_info[ "num" ] ]);
            if ($stock_result[ "code" ] < 0) {
                return $store_goods_sku_model->error([], '当前门店库存不足,请选择其他门店');
            }
            return $stock_result;
        }
    }

}